package org.client.iot.ui.account;

import android.annotation.SuppressLint;
import android.util.Base64;

import com.bumptech.glide.Glide;
import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;

import org.client.iot.LauncherApplication;
import org.client.iot.R;
import org.client.iot.databinding.ActivitySignBinding;
import org.client.iot.domain.CaptchaImageDto;
import org.client.iot.domain.LoginDto;
import org.client.iot.http.ApiService;
import org.client.iot.ui.project.ProjectHomeActivity;
import org.client.iot.util.MMKVUtils;
import org.client.iot.view.LoadingDialog;
import org.tzw.template.base.BaseActivity;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SignActivity extends BaseActivity<ActivitySignBinding> {
    private CaptchaImageDto captchaImageDto;

    @Override
    protected void initView() {
        getCaptchaImg();
        if ((Boolean) MMKVUtils.getInstance().get("agree", false)) {
            mRoot.checkboxAgree.setChecked(true);
            if (!(MMKVUtils.getInstance().get("token", "")).equals("")) {
                redirectToActivity(ProjectHomeActivity.class);
            }
        } else {
            mRoot.checkboxAgree.setChecked(false);
        }
    }

    @Override
    protected void initListener() {
        mRoot.btnLogin.setOnClickListener(v -> {
            if (!mRoot.checkboxAgree.isChecked()) {
                showToastLong("请先同意用户协议和隐私政策");
                return;
            }
            String userName = Objects.requireNonNull(mRoot.editAccount.getText()).toString();
            String pwd = Objects.requireNonNull(mRoot.edtPassword.getText()).toString();
            String captcha = Objects.requireNonNull(mRoot.edtCaptcha.getText()).toString();
            if (!userName.isEmpty() && !pwd.isEmpty() && !captcha.isEmpty()) {
                if (captchaImageDto != null) {
                    login(userName, pwd, captcha, captchaImageDto.getUuid());
                } else {
                    showToastLong("验证码已失效");
                }

            } else if (userName.isEmpty()) {
                showToastLong("请输入账号");
            } else if (pwd.isEmpty()) {
                showToastLong("请输入密码");
            } else {
                showToastLong("请输入验证码");
            }
        });
//        mRoot.settingImg.setOnClickListener(v -> {
//            redirectToActivity(SettingActivity.class);
//        });
        mRoot.imgCaptcha.setOnClickListener(v -> {
            getCaptchaImg();
        });

        mRoot.checkboxAgree.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                MMKVUtils.getInstance().put("agree", true);
                mRoot.checkboxAgree.setTextColor(getResources().getColor(android.R.color.white));
            } else {
                MMKVUtils.getInstance().put("agree", false);
                mRoot.checkboxAgree.setTextColor(getResources().getColor(android.R.color.darker_gray));
            }
        });
    }

    private void getCaptchaImg() {
        Observable<CaptchaImageDto> compose = NetworkApi.createService(ApiService.class,"").getCaptchaImage()
                .compose(NetworkApi.applySchedulers(new BaseObserver<CaptchaImageDto>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(CaptchaImageDto captchaImageDto) {
                        if (captchaImageDto == null) {
                            return;
                        }
                        SignActivity.this.captchaImageDto = captchaImageDto;
                        runOnUiThread(() -> {
                            Glide.with(LauncherApplication.getContext()).load((Base64.decode(captchaImageDto.getImg(), Base64.DEFAULT))).fitCenter().into(mRoot.imgCaptcha);
                        });
                        if ("验证码错误".equals(captchaImageDto.getMsg())) {
                            getCaptchaImg();
                        } else if ("验证码已失效".equals(captchaImageDto.getMsg())) {
                            getCaptchaImg();
                        }
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        requestFailed(e.getMessage());
                    }

                }));
    }

    private void login(String username, String password, String captcha, String uuid) {
        LoadingDialog loadingDialog = new LoadingDialog(this,"登录中...", R.mipmap.ic_dialog_loading);
        loadingDialog.show();
        String params = FastjsonUtils.toJsonString(loginParams(username, password, captcha, uuid));
        Observable<LoginDto> compose = NetworkApi.createService(ApiService.class,"").login(RequestBody.create(MediaType.parse("application/json"),
                        params))
                .compose(NetworkApi.applySchedulers(new BaseObserver<LoginDto>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onSuccess(LoginDto loginDto) {
                        loadingDialog.dismiss();
                        if (loginDto == null) {
                            return;
                        }
                        LogUtils.i("loginDto==", loginDto.toString());
                        if (loginDto.getCode() == 200) {
                            runOnUiThread(() -> {
                                MMKVUtils.getInstance().put("token", loginDto.getToken());
                                showToastShort("登录成功");
                                redirectToActivity(ProjectHomeActivity.class);
                                finish();
                            });
                        } else {
                            requestFailed(loginDto.getMsg());
                            getCaptchaImg();
                        }
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        loadingDialog.dismiss();
                        requestFailed(e.getMessage());
                    }

                }));
    }

    private Map<String, Object> loginParams(String username, String password, String captcha, String uuid) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("code", captcha);
        params.put("username", username);
        params.put("password", password);
        params.put("appId", "3rd");
        params.put("uuid", uuid);
        return params;
    }

    private void requestFailed(String msg) {
        runOnUiThread(() -> showToastLong(msg));
    }

}